//
//  ShopDetailsController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/14.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "ShopDetailsController.h"
#import "ConfirmOrderController.h"

#import "AddShopCarView.h"
#import "ShopFirstCell.h"
#import "ShopSecondCell.h"
#import "ShopThirdCell.h" 

#import "StandardsView.h"
#import "ShopWebViewController.h"
#import "ShopCarViewController.h"
#import "DOPScrollableActionSheet.h"
#import <UMSocialData.h>
#import <UMSocialSinaSSOHandler.h>
#import <UMSocialSnsService.h>
#import <UMSocialSnsPlatformManager.h>
#import "LogInViewController.h"


@interface ShopDetailsController ()<AddShopCarViewDelegate,StandardsViewBtnDelegate,UITableViewDelegate,UITableViewDataSource,UMSocialUIDelegate>
{
    MBProgressHUD *progressHUD;
    XRCarouselView *_XrCarouselView;
    NSArray *_cycleArray;
    //区分加入购物车 立即购买
    BOOL _selectStuas;
    NSDictionary *_urlDict;
    
    //判断规格是否为空
    NSString *_judgeColor;
    NSString *_judgeSize;
    NSString *_judgeFeilv;
}

@property(nonatomic,strong)UITableView *detailsView;
@property(nonatomic,strong)StandardsView*StandardsView;

@property(nonatomic,strong)NSDictionary *goodsDetailDict;

//尺码
@property(nonatomic,strong)NSArray *sizeArray;
//颜色
@property(nonatomic,strong)NSArray *colorArray;
/**
 *  费率
 */
@property(nonatomic,strong)NSArray *feilvArray;

@end

@implementation ShopDetailsController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //菊花加载
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    
    //商品详情请求
    [self getMoreDetailsRequestData];
    

}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"商品详情";
    
    [self addViews];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithBackgroundImage:[UIImage imageNamed:@"shopCar"] highBackgroundImage:nil target:self action:@selector(pushShopCarDidClick) title:nil];

}

//push购物车
- (void)pushShopCarDidClick
{
    ShopCarViewController *ShopCarVC = [[ShopCarViewController alloc] init];
    ShopCarVC.isPushCar = YES;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:ShopCarVC];
}


- (void)addViews
{
  
    UITableView *detailsView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, WIDTH,HEIGHT) style:UITableViewStyleGrouped];
    [self.view addSubview:detailsView];
    self.detailsView = detailsView;
    detailsView.delegate =self;
    detailsView.dataSource = self;
    detailsView.rowHeight = UITableViewAutomaticDimension;
    detailsView.estimatedRowHeight = 44;

    
    //分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0,HEIGHT/12*11-65, WIDTH, 1)];
    lineView.backgroundColor = [UIColor blackColor];
    lineView.alpha = 0.1;
    [self.view addSubview:lineView];
//    
    AddShopCarView *addView = [[AddShopCarView alloc] initWithFrame:CGRectMake(0,HEIGHT/12*11-64, WIDTH, HEIGHT/12)];
    [self.view addSubview:addView];
    addView.delegate= self;

}


#pragma mark >>>>>>获取id并请求数据
- (void)getMoreDetailsRequestData
{
    
    
    NSDictionary *params = @{@"id":[NSString stringWithFormat:@"%@",_goodsId],
                             @"username":@"",
                             @"clear_cache":@"1"
                             };
//    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/goods/info" completeBlock:^(id object) {
        
        if (JudgeBackDataCode) {
            
            NSDictionary *goodsDetailDict = [object objectForKey:@"data"];
            self.goodsDetailDict = goodsDetailDict;
            
            //轮播
            _cycleArray = [[NSArray alloc] init];
            _cycleArray = goodsDetailDict[@"xiaotu"];
            
            //图片地址
            _urlDict = goodsDetailDict[@"picprex"];
            
#warning 商品规格如果为空 返回字符串类型"" 有数据返回类型数组
            //尺码
            if ([goodsDetailDict[@"chima"] isKindOfClass:[NSString class]]) {
                _judgeSize = goodsDetailDict[@"chima"];
            }else{
                _sizeArray = goodsDetailDict[@"chima"];
            }
           
            //颜色
            if ([goodsDetailDict[@"yanse"] isKindOfClass:[NSString class]]) {
                _judgeColor = goodsDetailDict[@"yanse"];
            }else{
                self.colorArray = goodsDetailDict[@"yanse"];
            }
            
            //费率
            if ([goodsDetailDict[@"feilv"] isKindOfClass:[NSString class]]) {
                _judgeFeilv = goodsDetailDict[@"feilv"];
            }else{
                _feilvArray = goodsDetailDict[@"feilv"];
            }
            

            
            NSLog(@"%@",object);
//            NSLog(@"%@",_colorArray);
            
        }   
        
        [progressHUD hide:YES];
        [self.detailsView reloadData];
        
    }];
}


#pragma mark>>>>>>>>>>>>>>>收藏
//点击收藏
- (void)collectionDelegateBtnDidClick:(UIButton *)button{
    
    //用户是否登录
    if (![JudgeUserLogInTool JudgeUserLonInStatus:self.view]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    NSDictionary *params = @{@"id":[NSString stringWithFormat:@"%@",_goodsId],
                             @"type":[NSString stringWithFormat:@"%d",1],
                             @"username":[NSString stringWithFormat:@"%@",USERNAME],
                             };
//    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/goods/addFavorite" completeBlock:^(id object) {
         NSLog(@"%@",object);
        
        if (JudgeBackDataCode) {
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"收藏成功" toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
            
            button.selected = false;
            
        }else{
            
            button.selected = YES;
        }
        
        
    }];
}


#pragma mark>>>>>>>>>>>>>>>分享
- (void)shareDelegateBtnDidClick
{
    [UMSocialData defaultData].extConfig.title = @"亿乐购物吧,给你想要的";
    [UMSocialData defaultData].extConfig.qqData.url = @"http://baidu.com";
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"57ac185467e58e1d4e002843"
                                      shareText:@"亿乐购物吧,给你想要的，http://baidu.com"
                                     shareImage:[UIImage imageNamed:@"tubiao108"]
                                shareToSnsNames:@[UMShareToSina,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToWechatFavorite]
                                       delegate:self];
    
    /*
     @[UMShareToSina,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToWechatFavorite,UMShareToQzone,UMShareToQQ]
     */
}

- (void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response {
    if (response.responseCode == UMSResponseCodeSuccess) {
        NSLog(@"分享成功");
    }
}

#pragma mark>>>>>>>>>>>>>>>加入购物车 立即购买
- (void)AddShopCarViewDidClick:(UIButton *)button
{
    
    //用户是否登录
    if (![JudgeUserLogInTool JudgeUserLonInStatus:self.view]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        return;
    }
    
//    判断有无库存
    if (![self judeKucunAlertVIewShow]) {
        return;
    }
    
    //尺码款式没有->直接购买或者加入购物车
//    [self addShoppingCartNetworkRequests];
    
    //商品规格view
    [self buildStandardsView];

    //加入购物车
    if (button.tag == 2000) {
        
        _selectStuas = YES;
        
    }else{
      
    //立即购买-->确认订单
        _selectStuas = false;
    }
}

//点击X或者透明消失
-(void)StandardsViewCancleBtnDidMiss:(UIButton *)button
{
    [_StandardsView dismissStandardsView];
}

//点击确定代理方法
-(void)StandardsViewConfirmBtnClick:(UIButton *)button sizeStr:(NSString *)sizeStr colorStr:(NSString *)colorStr num:(NSString *)numStr feilvStr:(NSString *)feilvStr
{
    [_StandardsView dismissStandardsView];
    if (_selectStuas) {
       
        NSLog(@"加入购物车");
        [self addShoppingCartNetworkRequests:sizeStr colorStr:colorStr num:numStr feilvStr:feilvStr];
        
        
    }else{
        
        ConfirmOrderController *ConfirmOrderVC = [[ConfirmOrderController alloc] init];
        [self.navigationController pushForm:self.navigationController pushToAndHidden:ConfirmOrderVC];
    }

}

#pragma mark >>>>>>>>>> 商品添加到购物车
- (void)addShoppingCartNetworkRequests:(NSString *)sizeStr colorStr:(NSString *)colorStr num:(NSString *)numStr feilvStr:(NSString *)feilvStr
{

    
    NSDictionary *params = @{@"pid":[NSString stringWithFormat:@"%@",_goodsId],
                             @"username":[NSString stringWithFormat:@"%@",USERNAME],
                             @"chima":[NSString stringWithFormat:@"%@",sizeStr],
                             @"yanse":[NSString stringWithFormat:@"%@",colorStr],
                             @"num":numStr,
                             @"feilv":[NSString stringWithFormat:@"%@",feilvStr]
                             };
    NSLog(@"%@",params);
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cart/add" completeBlock:^(id object) {

         NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"亲~快去购物车结算吧!" toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        }else{
            
            NSDictionary *dict = [object objectForKey:@"message"];
            MBProgressHUD *hud = [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",dict[@"msg"]] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        }
          
    }];
    
}


- (void)StandardViewCellDelegate:(NSString *)selectStr
{
    NSLog(@"%@",selectStr);
}

#pragma mark >>>>>>>>>> 商品规格
- (void)buildStandardsView
{
    self.StandardsView = [[StandardsView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT)];
    self.StandardsView.delegate = self;
#warning 
    
    if (!_judgeColor) {
        _StandardsView.colorArray = _colorArray;
    }
   
    if (!_judgeSize) {
        _StandardsView.sizeArray = _sizeArray;
    }

    
    if (!_judgeFeilv) {
       _StandardsView.feilvArray = _feilvArray;
    }
    //name
    _StandardsView.nameLabel.text = [NSString stringWithFormat:@"%@",self.goodsDetailDict[@"title"]];
    //价格
    _StandardsView.saleLabel.text = [NSString stringWithFormat:@"¥ %@",self.goodsDetailDict[@"huiyuanjia"]];

    //图片
    NSString *string = [NSString stringWithFormat:@"%@%@",_urlDict[@"m"],_goodsDetailDict[@"picurl"]];
    [_StandardsView.goodsImg  sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"businessNopict.jpg"]];
    
    //规格show
    [_StandardsView showStandardsView];
}

//判断有无库存
- (BOOL)judeKucunAlertVIewShow
{
    //判断is_kucun 0代表无库存 1为有库存
    if ([_goodsDetailDict[@"is_kucun"] isEqual:@(0)]) {
        
        //弹框
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"此商品已下架" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [hud show:YES];
        
        return NO;
        
    }else{
        
        return YES;
    }
    
}

#pragma mark>>>>>>>>数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 0;
    }else if(section ==1){
        return 1;
    }else if(section ==2){
        return 2;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0) {
        return nil;
    }else if (indexPath.section ==1){
        ShopFirstCell *cell= [[ShopFirstCell alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.nameLabel.text = self.goodsDetailDict[@"title"];
        cell.brandLabel.text = [NSString stringWithFormat:@"品牌:%@",self.goodsDetailDict[@"pinpai"]];
        cell.saleLabel.text = [NSString stringWithFormat:@"¥%@",self.goodsDetailDict [@"huiyuanjia"]];
        cell.totalLabel.text = [NSString stringWithFormat:@"¥%@",self.goodsDetailDict [@"shichangjia"]];
        
        //判断is_kucun 0代表无库存 1为有库存
        if ([_goodsDetailDict[@"is_kucun"] isEqual:@(0)]) {
            cell.kucun = [NSString stringWithFormat:@"%@",self.goodsDetailDict[@"kucun"]];
        }else{
             cell.kucun = [NSString stringWithFormat:@"销量%@件",self.goodsDetailDict[@"kucun"]];
        }
        
        cell.sale = [NSString stringWithFormat:@"销量 %@件",self.goodsDetailDict[@"sales"]];
        
        return cell;
    }else if(indexPath.section ==2){
       
        if (indexPath.row ==0) {
            ShopSecondCell *cell = [ShopSecondCell loadShopSecondCellView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.commentLabel.text = @"商品评论 30";
            cell.commentLabel.font = [UIFont systemFontOfSize:13];
            return cell;
        }else{
            
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    }else{
        
        if (indexPath.row == 0) {
            ShopSecondCell *cell = [ShopSecondCell loadShopSecondCellView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.commentLabel.text = @"图文详情";
            cell.moreButton.hidden = YES;
            cell.commentLabel.font = [UIFont systemFontOfSize:13];
            return cell;
        }else{
            
            ShopThirdCell *cell = [[ShopThirdCell alloc] init];
                       
            cell.htmlStr = _goodsDetailDict[@"about"];
//            NSLog(@"%@",_goodsDetailDict[@"about"]);
            return cell;
        }
        
    }
    
}

#pragma mark>>>>>>>>代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return HEIGHT/2;
    }else if(section == 1){
        return 0.01;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 0.01;
    }else if (indexPath.section ==1){
        
        if (iPhone5) {
            return HEIGHT/4.5;
        }else if(iPhone6){
            return HEIGHT/5.5+5;
        }else{
            return HEIGHT/5.8+5;
        }
    }else if(indexPath.section ==2){
        
        if (indexPath.row ==0) {
            return HEIGHT/15;
        }else{
            return HEIGHT/5;
        }
    }else{
        
        if (indexPath.row ==0) {
            return HEIGHT/15;
        }else{
            return HEIGHT*1.5;
        }
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        NSMutableArray *imageArr = [NSMutableArray array];
        for (int i = 0; i < _cycleArray.count; ++i) {
            NSString *str = [NSString stringWithFormat:@"%@%@",_urlDict[@"focus"],_cycleArray[i]];
            [imageArr addObject:str];
        }
        
//        NSLog(@"%@",imageArr);
        
        _XrCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/2) imageArray:imageArr];
        _XrCarouselView.time = 2;
        [_XrCarouselView setPageColor:[UIColor whiteColor] andCurrentPageColor:DEFAULT_COLOR];
        return _XrCarouselView;
    }
    return nil;
}


@end
